<template>
  <div class="">
    <div class="title">{{ addForm.id==0?'添加公告':'修改公告' }}</div>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="addForm" :rules="rules" label-width="auto"
      class="demo-ruleForm" status-icon>
      <el-form-item label="标题" prop="title">
          <el-input v-model="addForm.title" aria-placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="公告内容" prop="content">
         <RichText v-model:content="addForm.content"></RichText>
      </el-form-item>
      <el-form-item label="公告照片" prop="picture">
        <el-upload
        :headers="headers"
    class="avatar-uploader"
    :action="updataurl+'upload/add'"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="addForm.picture" :src="baseUrl+addForm.picture" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-radio-group v-model="addForm.state">
        <el-radio  :value=0>显示</el-radio>
        <el-radio  :value=1>隐藏</el-radio>
      </el-radio-group>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select
        v-model="addForm.type"
        placeholder="请选择类型">
        <el-option v-for="(item,index) in newstype" :key="item.id"  :value="item.id" :label="item.name"  />
      </el-select>
      </el-form-item>
      <el-form-item label="" prop="name">
        <el-button type="primary" @click="onSubmit">{{addForm.id==0?"添加":"修改"}}</el-button>
        <el-button @click="router.go(-1)">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang='ts' setup>
import { ref, watch,onMounted, reactive, onBeforeMount } from "vue"
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import  { useStore } from '../../store/index'
import { storeToRefs } from "pinia"
import { newstypelist,newsadd,newsonelist } from "../../service/news/news"
import moment  from "moment"
import { useRoute, useRouter } from "vue-router"
import RichText from "../../components/RichText.vue"

type newstype = {
  id: number;
  name: string;
}
const newstype = ref<newstype[]>([])
const usestore = useStore()
const {token} = storeToRefs(usestore)
// 图片根路径
const baseUrl = import.meta.env.VITE_IMG_URL
const updataurl = import.meta.env.VITE_BASE_URL
const imgUrl = ref('')
const headers = {
  'Authorization': token.value
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
) => {
    if (response.errCode === 10000) {
        addForm.picture = response.data;
    }
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('文件应为png或jpg格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('文件大小不能超过2M!')
    return false
  }
  return true
}

type addType = {
  id: number;
  title: string;
  picture: string;
  edituser: string;
  state: number;
  type: number | null;
  hits: number;
  content: string;
  addtime: string;
}
const addForm = reactive<addType>({
  id: 0,
  title: "",
  picture: "",
  edituser: "",
  state:0 ,
  type: null,
  hits: 0,
  content: "",
  addtime: moment().format('YYYY-MM-DD HH:mm:ss'),
})

const rules = reactive<FormRules<addType>>({
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
  ],
  picture: [
    { required: true, message: '请输入标题', trigger: 'blur' },
  ],
  state: [
    { required: true, message: '请输入标题', trigger: 'blur' },
  ],
  content: [
    { required: true, message: '请输入标题', trigger: 'blur' },
  ],
  type: [
    { required: true, message: '请输入标题', trigger: 'blur' },
  ],
})

  const router = useRouter()
  const ruleFormRef = ref<FormInstance>()
  const onSubmit =  () => {
    ruleFormRef.value?.validate((valid, fields) => {
        if (valid) {
          onSubmits()
        }
    })
}
const onSubmits =async ()=>{
  let res:any = await newsadd(addForm)
  if (res.errCode === 10000) {
    ElMessage.success('添加成功')
   return router.go(-1)
  }
  ElMessage.warning('添加失败')
}

const getnewsonelist = async()=>{
  console.log(111);
  let res:any = await newsonelist(addForm.id)
  console.log(res);
  
  if (res.errCode === 10000) {
   Object.assign(addForm,res.data)
  }
}


onBeforeMount(()=>{
  const route = useRoute()
  addForm.id = route.query.id as unknown as number

})


onMounted(()=>{
  newstypelist().then(res=>{
    newstype.value = res.data.list
  })
  if (addForm.id!=0) {
    getnewsonelist()
  }
})


</script>

<style scoped>

.avatar-uploader .avatar {
  width: 78px;
  height: 78px;
  display: block;
}
/deep/ .avatar-uploader .el-upload {
  width: 80px;
  height: 80px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
</style>
